<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<title>OrbitControls控制器案例</title>
		<style type="text/css">
			html,
			body {
				margin: 0;
				height: 100%;
			}

			canvas {
				display: block;
			}

			/* 进度条 */
			.progress {
				position: fixed;
				width: 100%;
				height: 100%;
			}

			.progress .mask {
				position: fixed;
				width: 100%;
				height: 100%;
				background: rgba(0, 0, 0, 0.2);
				z-index: 99;
			}

			.progress .loading {
				width: 30em;
				height: 1em;
				background: #fff;
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				z-index: 100;
				border-radius: 1em;
			}

			.progress .trends {
				width: 0;
				height: 100%;
				background: rgba(255, 0, 255, .5);
				box-shadow: 1px 1px 10px rgba(0, 0, 255, .5);
				border-radius: 1em;
			}

			.ctrlWrap {
				width: 150px;
				height: 40px;
				position: absolute;
				bottom: 10px;
				left: 50%;
				transform: translateX(-50%);
				background-color: rgba(255, 255, 255, .3);
				z-index: 10;
				display: flex;
				justify-content: space-around;
				align-items: center;
				color: #FFF;

			}

			.ctrlWrap span {
				width: 40px;
				height: 30px;
				line-height: 30px;
				text-align: center;
				border: 1px solid #333;
				border-radius: 5px;
				padding: 2px;
				background-color: rgba(0, 0, 255, .5);
				cursor: pointer;
			}
		</style>
	</head>
	<body onload="draw();">
		<div class="ctrlWrap">
			<span id="open">开</span>
			<span id="close">关</span>
		</div>
		<div id="progress" class="progress">
			<div class="mask"></div>
			<div class="loading">
				<div class="trends"></div>

			</div>
		</div>
	</body>

	<script src="./js/three.js"></script>

	<script src="./js/OrbitControls.js"></script>
	<script src="./js/GLTFLoader.js"></script>
	<script src="./js/stats.min.js"></script>
	<script src="./js/Tween.js"></script>

	<script>
		console.log(THREE.REVISION)
		var renderer, camera, scene, controls;
		//监听帧率
		var stats;
		var pointLight;

		var mixer = new THREE.AnimationMixer();
		var clock = new THREE.Clock();
		var clipAction
		var animationClip

		//阀门模型
		var valveModel;
		var ValveFlag = true

		function initRender() {
			renderer = new THREE.WebGLRenderer({
				antialias: true
			});
			renderer.setSize(window.innerWidth, window.innerHeight);
			//告诉渲染器需要阴影效果
			renderer.shadowMap.enabled = true;
			renderer.outputEncoding = THREE.sRGBEncoding;

			renderer.shadowMap.type = THREE.PCFSoftShadowMap; // 默认的是，没有设置的这个清晰 THREE.PCFShadowMap
			document.body.appendChild(renderer.domElement);
		}

		function initCamera() {
			camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
			camera.position.set(0, 30, 30);
			camera.lookAt(new THREE.Vector3(0, 0, 0));


		}

		function initScene() {
			scene = new THREE.Scene();
			scene.background = new THREE.Color(0xa0a0a0);

		}


		//灯光
		function addLight() {

			const light = new THREE.DirectionalLight(0xffffff)
			light.position.set(0, 500, 500)

			light.castShadow = true
			light.shadow.camera.top = 100
			light.shadow.camera.bottom = -100
			light.shadow.camera.left = -100
			light.shadow.camera.right = 100

			//告诉平行光需要开启阴影投射
			light.castShadow = true
			scene.add(light)



		}

		function addPointLights() {
			pointLight = new THREE.PointLight(
				0xffffff, // 光照颜色,默认 0xffffff
				1 // 光照强度, 光照强度 默认 1
			);
			// 设置光源位置
			pointLight.position.set(15, 40, 35);
			// 从光源到光照强度为0的位置。当设置为0时，光永远不会消失(距离无穷大)
			pointLight.distance = 0;
			// 是否开启点光源
			pointLight.visible = true;
			// 将点光源添加到场景中
			scene.add(pointLight)


			// PointLight( color, intensity, distance, decay )
			/* 	pointLight = new THREE.PointLight(0xffffff, 10, 100);
				pointLight.position.set(30, 50, 10);
				scene.add(pointLight); */

			// PointLightHelper( light：点光, sphereSize:点光对象的大小, color：颜色 )
			/* var sphereSize = 5;
			var pointLightHelper = new THREE.PointLightHelper(pointLight, sphereSize);
			scene.add(pointLightHelper); */

			//点光2
				/* var pointLight1 = new THREE.PointLight(0xffffff, 1, 100);
				pointLight1.position.set(-30,100, 100);
				pointLight1.position.set(30,15, 0);
				scene.add(pointLight1);
				
				var sphereSize1 = 5;
				var pointLightHelper1 = new THREE.PointLightHelper(pointLight1, sphereSize1);
			scene.add(pointLightHelper1); */
		}

		function floor() {


			// 创建具有镜面高光的光泽表面的材质
			// 颜色 0xffffff dithering 是否对颜色应用抖动以消除条带的外观
			var material = new THREE.MeshPhongMaterial({
				color: 0x808080,
				dithering: true
			});
			// 创建一个缓冲平面 长宽
			var geometry = new THREE.PlaneBufferGeometry(300, 300);
			// 创建网格对象 物体 材质
			var mesh = new THREE.Mesh(geometry, material);
			// 设置网格对象的位置
			mesh.position.set(0, -10, 0);
			// 沿着X轴旋转
			mesh.rotation.x = -Math.PI * 0.5;
			// 接受阴影
			mesh.receiveShadow = true;
			// 将网格对象添加到场景中
			scene.add(mesh);

		}

		function initModel() {
			var loader = new THREE.GLTFLoader();
			loader.load('./models/v1_jian.glb', function(gltf) {
				// 调节模型大小比例
				// gltf.scene.scale.set(10, 10, 10);
				// 调节模型位置
				// gltf.scene.position.set(0, 20, 0);

				console.log(gltf)
				scene.add(gltf.scene);

				valveModel = gltf.scene.getObjectByName("阀门")

				var hou = gltf.scene.getObjectByName("后盖")


				function changeColor(obj, color) {
					obj.traverse(function(item) {
						if (item instanceof THREE.Mesh) {
							item.castShadow = true;
							item.receiveShadow = true;
							item.material = new THREE.MeshBasicMaterial({

								color: color,
								transparent: true,
								opacity: 0.3 //设置透明度
							});
						}
					})
				}
				// changeColor(hou, "#F00")
				const texture1 = new THREE.TextureLoader().load('./img/小格子.png'); // 纹理加载器
				texture1.wrapS = THREE.RepeatWrapping;
				texture1.wrapT = THREE.RepeatWrapping;
				texture1.repeat.set(3, 3);
				
				const texture0 = new THREE.TextureLoader().load('./img/小格子.png'); // 纹理加载器
				texture0.wrapS = THREE.RepeatWrapping;
				texture0.wrapT = THREE.RepeatWrapping;
				// texture1.repeat.set(3, 3);
				
				const texture = new THREE.TextureLoader().load('./img/透明边.png'); // 纹理加载器
				texture.wrapS = THREE.RepeatWrapping;
				texture.wrapT = THREE.RepeatWrapping;
				gltf.scene.traverse((child) => {
					if (child.isMesh && child.name.includes("后盖")) {
						child.material = new THREE.MeshPhysicalMaterial({
							map: texture0,
							color: 0xffffff,
							metalness: 0,
							roughness: 0,
							transmission: 1,
							transparent: true,
							opacity: .5,
							ior: 5,
							/* color: "#FFF",
							metalness: 0,
							roughness: 0,
							transmission: .3,
							transparent: true,
							opacity: .5,
							ior: 1.52, //折射率
							//厚度 透过看物体的模糊程度
							thickness: 1,
							//镜面强度
							specularIntensity: 1, */


						});
					}

					if (child.isMesh && child.name.includes("后盖透明纹理")) {
						child.material = new THREE.MeshPhysicalMaterial({
							map: texture1,  //小格子
							side: THREE.DoubleSide,
							color: "#96B1D2",
							metalness: 0, //金属
							roughness: 0, //粗糙
							transmission: 1,
							transparent: true,
							opacity:1,
						});
					}
					
					if (child.isMesh && child.name.includes("后盖内层")) {
						child.material = new THREE.MeshPhysicalMaterial({
							map: texture,
							side: THREE.DoubleSide,
							color: "#2A73AB",
							metalness: 0, //金属
							roughness: 0, //粗糙
							transmission: 1,
							opacity:.5,
							transparent: true,
						});
					}
					
					
				})
				

			}, onProgress, onError);

		}



		//进度通知
		function onProgress(xhr) {
			// console.log(xhr)
			if (xhr.lengthComputable) {
				var percentComplete = xhr.loaded / xhr.total * 100;
				console.log(Math.round(percentComplete, 2) + '% downloaded');
				loadStats(Math.round(percentComplete, 2))
			}
		};
		//加载模型报错通知
		function onError(xhr) {
			console.log("加载GLTF错误" + xhr)
		};

		function loadStats(a) {
			document.getElementsByClassName("trends")[0].style.width = a + "%";
			document.getElementsByClassName("trends")[0].innerHTML = a + '%';
			if (a < 100) {
				document.getElementById("progress").style.display = "block";
			} else {
				document.getElementById("progress").style.display = "none";
			}
		}

		function initStats() {
			stats = new Stats();
			document.body.appendChild(stats.dom);
		}

		function initControl() {

			controls = new THREE.OrbitControls(camera, renderer.domElement);
			// 使动画循环使用时阻尼或自转 意思是否有惯性
			controls.enableDamping = true;

			// 设置控制器是否可以旋转以及旋转速度
			controls.enableRotate = true;
			controls.rotateSpeed = .5;
			//动态阻尼系数 就是鼠标拖拽旋转灵敏度
			controls.dampingFactor = 0.25;
			//是否可以缩放
			controls.enableZoom = true;
			controls.zoomSpeed = 1.0;
			//是否自动旋转
			controls.autoRotate = false;
			controls.autoRotateSpeed = 0.5;
			//设置相机距离原点的最远距离
			controls.minDistance = 10;
			//设置相机距离原点的最远距离
			controls.maxDistance = 4000;
			//是否开启右键拖拽
			controls.enablePan = false;
		}


		function openValve() {

			if (ValveFlag) {
				new TWEEN.Tween(valveModel.rotation)
					.to({
						x: 0,
						y: 0,
						z: 0
					}, 2000)
					.onUpdate(function(val) {
						valveModel.rotation.set(val.x || 0, val.y || 0, val.z || 0);
					})
					.start();
				ValveFlag = !ValveFlag;
			} else {
				alert("已经是打开的状态")
			}
		}

		function closeValve() {
			// 开关门动作
			if (ValveFlag === false) {
				new TWEEN.Tween(valveModel.rotation)
					.to({
						x: 0,
						y: Math.PI / 2,
						z: 0
					}, 1000)
					.onUpdate(function(val) {
						valveModel.rotation.set(val.x || 0, val.y || 0, val.z || 0);
					})
					.start();
				ValveFlag = !ValveFlag;
			} else {
				alert("已经是关闭的状态")
			}
		}



		function render() {

			controls.update();
			//让点光跟随相机的参照点
			var vector = camera.position.clone();
			pointLight.position.set(vector.x, vector.y, vector.z); //点光源位置

			renderer.render(scene, camera); //执行渲染操作
			//console.log(vector.x);



			renderer.render(scene, camera);
		}

		function onWindowResize() {

			camera.aspect = window.innerWidth / window.innerHeight;
			camera.updateProjectionMatrix();
			renderer.setSize(window.innerWidth, window.innerHeight);

		}

		function update() {

			// controls.update();
			stats.update();
		}


		function animate() {
			TWEEN.update();
			//更新控制器
			render();
			update();

			/* var delta = clock.getDelta();
			mixer.update(delta); */
			//更新性能插件
			stats.update();

			requestAnimationFrame(animate);
		}

		function draw() {
			initRender();
			initScene();
			initCamera();
			addPointLights()
			addLight()
			// floor();
			initStats();
			initModel()

			initControl();

			animate();
			window.onresize = onWindowResize;
			document.getElementById("open").addEventListener('click', openValve)
			document.getElementById("close").addEventListener('click', closeValve)

		}
	</script>
</html>
